/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Servlets;

import DAO.DAOFactory;
import DAO.DAOinterface;
import DAO.ProyectoDAO;
import DAO.exceptions.NonexistentEntityException;
import Entidad.Proyecto;
import Entidad.Rol;
import Facade.FacadeFactory;
import VO.CodigoVO;
import VO.ProyectoVO;
import VO.RolVO;
import VO.UsuarioVO;
import java.io.IOException;
import java.io.PrintWriter;
import javax.faces.application.Application;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import App.Sesion;

/**
 *
 * @author David
 */
public class ServletRegister extends HttpServlet {
    
    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String tipoError = "";
        try {
            String txtNombre = (request.getParameter("nombre"));
            String txtApellido = (request.getParameter("apellidos"));
            String txtCorreo = (request.getParameter("correo"));
            if(request.getParameter("nombre").equals(""))
                tipoError = tipoError + " Nombre,";
            if(request.getParameter("apellidos").equals("")) 
                tipoError = tipoError + " Apellidos,";
            if(request.getParameter("correo").equals(""))
                tipoError = tipoError + " Correo,";
            if(request.getParameter("password").equals(""))
                tipoError = tipoError + " Contraseña,";
            if(!request.getParameter("password").equals("") && !request.getParameter("password").equals(request.getParameter("password2")))
                tipoError = tipoError + " Contraseñas no coinciden,";
            if(request.getParameter("codigo").equals(""))
                tipoError = tipoError + " Código.";
            String error = "Campos Faltantes: "+tipoError;
            if(!tipoError.equals(""))
               response.sendRedirect("registro.jsp?error=" + error +"&nombre="+txtNombre+"&apellido="+txtApellido+"&correo="+txtCorreo);
            else {
               String codigo = request.getParameter("codigo");
               CodigoVO codigoVoBD = FacadeFactory.createFacade().validateCode(codigo);
               if(codigoVoBD != null && codigo.equals(codigoVoBD.getCodigodeactivacion()) && codigoVoBD.getUsado()==false) {
                  UsuarioVO userVo = new UsuarioVO();
                  RolVO rolVo = new RolVO(); 
                  userVo.setNombre(request.getParameter("nombre"));
                  userVo.setApellido(request.getParameter("apellidos"));
                  userVo.setCorreo(request.getParameter("correo"));
                  userVo.setClave(request.getParameter("password"));
                  rolVo.setIdrol(2);
                  Rol rol = rolVo.toEntity();
                  userVo.setIdrol(rol);
                  userVo.setIdproyecto(null);
                  ProyectoVO proyectoVo = FacadeFactory.createFacade().showProject(1);
                  Proyecto proyecto = proyectoVo.toEntity();
                  userVo.setIdproyecto(proyecto);
                  boolean state = FacadeFactory.createFacade().createManager(userVo);
                  if(state == false) {
                      tipoError = tipoError + " No te puedes registrar con ese correo";
                      error = "Error: "+tipoError;
                      response.sendRedirect("registro.jsp?error=" + tipoError);
                  }
                  else {
                      App.Sesion.setNombre(txtNombre);
                      App.Sesion.setApellido(txtApellido);
                      App.Sesion.setCorreo(txtCorreo);
                      response.sendRedirect("crearProyecto.jsp?usuario="+request.getParameter("correo"));
                  }
               }
               else {
                 throw new NonexistentEntityException("Codigo "+codigo+" no encontrado");
               }
            }
        } 
        catch(NonexistentEntityException e) {
            tipoError = tipoError + " Código Inválido";
            String error = "Error: "+tipoError;
            response.sendRedirect("registro.jsp?error=" + error);
        }
        finally {            
            out.close();
        }
    }

    
    
    
    
    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
